package com.hanbang.chu_xing_gao_zhao.application;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.entity.UserInforData;
import com.hanbang.chu_xing_gao_zhao.module.LogInActivity;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog.MODE;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyLocationUtils;
import com.hanbang.chu_xing_gao_zhao.utils.MyLocationUtils.locationCallback;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.view_dynamic.DynamicActivity;
import com.hanbang.chu_xing_gao_zhao.view_find.FindMainFragmentActivity;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class WelcomeActivity extends BaseActivity {
    private MyLocationUtils myLocationUtils;
    // 处理消息
    Handler handler2 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (userData != null) {
                Intent intent = new Intent(WelcomeActivity.this, DynamicActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(WelcomeActivity.this, LogInActivity.class);
                startActivity(intent);
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);

        // 延迟两秒发送消息,显示欢迎界面。
        new Thread() {
            public void run() {
                try {
                    this.sleep(500);
                    handler2.sendEmptyMessage(-1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ;
        }.start();

        if (!isLogin(false)) {
            return;
        }
        uploadiogLocation();

    }

    /**
     * 获取用户的位置上传到服务器
     */
    private void uploadiogLocation() {

        myLocationUtils = new MyLocationUtils(this);

        /**
         * 获取位置信息传给服务器
         * */
        myLocationUtils.setOnClickCallback(new locationCallback() {

            @Override
            public void onClick(String location, double longitude, double latitude) {

                getDynamicList(location, longitude, latitude, 1);

            }
        });

    }

    private void next() {
        if (isLogin(false)) {
            // 检查密码的正确性
            verifyLogin();
        } else {
            // 未登录
            Intent intent2 = new Intent();
            intent2.setClass(WelcomeActivity.this, FindMainFragmentActivity.class);
            intent2.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent2);
            finish();
        }
    }

    HttpHandler<File> handler = null;

    private void getServiceVersion() {
        ((MyApplication) getApplication()).httpUtils.send(HttpMethod.GET, HttpInterfaces.updateApp + "&versioncode="
                + SystemTools.getVersionCode(this), new MyRequestCallBack<String>(this, null) {
            @Override
            public void onFailure(HttpException error, String msg) {
                super.onFailure(error, msg);
                next();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result.toString());
                    int status = json.getInt("status");
                    if (status == 1) {
                        String versionName = json.getString("versionName");
                        final String path = json.getString("path");
                        MyDialog dialog = new MyDialog(WelcomeActivity.this, R.style.base_dialog, MODE.CONFIRM);
                        dialog.setTitle("版本更新");
                        dialog.setContent("检测到新版本，当前版本" + SystemTools.getVersionName(WelcomeActivity.this) + ",最新版本"
                                + versionName + ",是否下载更新？");
                        dialog.setOnClickCallback(new MyDialog.OnClickCallback() {

                            @Override
                            public void onClick(MyDialog dialog, Object number, Object content) {
                                if ((Integer) number == 0 || (Integer) number == 1) {
                                    next();
                                } else if ((Integer) number == 2) {
                                    // 确定 下载
                                    final MyDialog dialog2 = new MyDialog(WelcomeActivity.this, R.style.base_dialog,
                                            MODE.PROGRESS);
                                    dialog2.setTitle("正在下载");
                                    dialog2.setOnClickCallback(new MyDialog.OnClickCallback() {

                                        @Override
                                        public void onClick(MyDialog dialog, Object number, Object content) {
                                            if (handler != null) {
                                                handler.cancel();
                                                MyToast.show(WelcomeActivity.this, "取消下载", Toast.LENGTH_SHORT);
                                                next();
                                            }
                                        }
                                    });
                                    dialog2.show();
                                    MyRequestCallBack<File> callBack = new MyRequestCallBack<File>(
                                            WelcomeActivity.this, null) {
                                        public void onSuccess(com.lidroid.xutils.http.ResponseInfo<File> responseInfo) {
                                            super.onSuccess(responseInfo);
                                            installApk(responseInfo.result);
                                            dialog2.dismiss();
                                        }

                                        ;

                                        public void onFailure(HttpException error, String msg) {
                                            super.onFailure(error, msg);
                                            dialog2.dismiss();
                                            next();
                                        }

                                        ;

                                        public void onLoading(long total, long current, boolean isUploading) {
                                            super.onLoading(total, current, isUploading);
                                            Float countMb = ((int) ((total / 1024.0 / 1024.0) * 100)) / 100.0f;
                                            Float currentMb = ((int) ((current / 1024.0 / 1024.0) * 100)) / 100.0f;
                                            dialog2.setProgress((int) (current / (total * 1.0) * 100));
                                            dialog2.setMb(countMb, currentMb);

                                        }

                                        ;
                                    };
                                    callBack.setRate(100);
                                    handler = ((MyApplication) getApplication()).httpUtils.download(
                                            SystemTools.getHttpFileUrl(path), MyApplication.otherPath + File.separator
                                                    + "mrcm.apk", callBack);
                                }
                            }
                        });

                        dialog.show();

                    } else {
                        next();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        });
    }

    // 安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivityForResult(intent, 990);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 990 && resultCode == 0) {
            // 取消安装了
            next();
        }
    }

    /*
     * 如果已经保存密码 那么就检查此密码的正确性
     */
    private void verifyLogin() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("action", "user_login");
        params.addBodyParameter("mobile", userData.getUser_name());
        params.addBodyParameter("password", userData.getPassword());
        httpUtils.send(HttpMethod.POST, HttpInterfaces.verificationNumber, params, new MyRequestCallBack<String>(this,
                null) {
            @Override
            public void onFailure(HttpException error, String msg) {
                super.onFailure(error, msg);
                Intent intent = new Intent();
                intent.setClass(WelcomeActivity.this, DynamicActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
                finish();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);
                    int status = json.getInt("status");
                    if (status == 1) {
                        UserInforData userInforData = JsonHelper.parseObject(json, UserInforData.class);
                        try {
                            dbUtils.saveOrUpdate(userInforData);
                            // 把id 保存在sp
                            MySharedPreferences.setSharedPreferencesKeyAndValue(WelcomeActivity.this,
                                    MySharedPreferences.USER_DATA, "user_id", userInforData.getId());
                            MyLog.e("login", "id保存成功");
                            Intent intent = new Intent();
                            intent.setClass(WelcomeActivity.this, DynamicActivity.class);
                            startActivity(intent);
                            finish();
                        } catch (DbException e) {
                            e.printStackTrace();
                            MyLog.e("login", "id保存失败");
                            MyToast.show(WelcomeActivity.this, "登录失败", Toast.LENGTH_SHORT);
                            MySharedPreferences.setSharedPreferencesKeyAndValue(WelcomeActivity.this,
                                    MySharedPreferences.USER_DATA, "user_id", -1);
                        }
                    } else if (status == -100) {
                        passwordIsError(true);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show(WelcomeActivity.this, "登录失败", Toast.LENGTH_LONG);
                }
                Intent intent = new Intent();
                intent.setClass(WelcomeActivity.this, DynamicActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

    }

    /**
     * @param location_name
     * @param longitude
     * @param latitude
     * @param Phonetype     手机类型
     */
    private void getDynamicList(String location_name, double longitude, double latitude, int Phonetype) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(WelcomeActivity.this,
                MySharedPreferences.USER_DATA, "tlephone"));
        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(WelcomeActivity.this,
                MySharedPreferences.USER_DATA, "password"));
        params.addBodyParameter("location_name", location_name + "");
        params.addBodyParameter("gps", longitude + "," + latitude);
        params.addBodyParameter("os", Phonetype + "");

        httpUtils.send(HttpMethod.POST, HttpInterfaces.RememberLocation, params, new MyRequestCallBack<String>(this,
                "页面加载中...") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {

                    JSONObject json = new JSONObject(responseInfo.result);

                    int result = json.getInt("Result");

                    if (result == 0) {
                        myLocationUtils.stop();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

}
